// grid和布局的全局变量
var sm;
var cm;
var store;
var grid;
var viewport;
var currentRowInd = 0;
var currentColInd;
var Plant;
Ext.onReady(function() {
	Ext.QuickTips.init();
	var sm = new Ext.grid.CheckboxSelectionModel();
	cm = new Ext.grid.ColumnModel([ new Ext.grid.RowNumberer(), sm, {
		header : 'id',
		dataIndex : 'id',
		hidden : true,
		width : 10
	}, {
		header : '名称(text)',
		dataIndex : 'title',
		editor : new Ext.form.TextField({
			allowBlank : false,
			blankText : "不允许为空"
		}),
		width : 120
	}, {
		header : '图标(iconCls)',
		dataIndex : "iconCls",
		menuDisabled : true,
		width : 120,
		editor : new Ext.form.TextField()
	}, {
		header : '次图标(iconClsChild)',
		dataIndex : "iconClsChild",
		menuDisabled : true,
		width : 120,
		editor : new Ext.form.TextField()
	}, {
		header : '事件(handler)',
		dataIndex : "handler",
		menuDisabled : true,
		width : 400,
		editor : new Ext.form.TextField({
			allowBlank : false,
			blankText : "不允许为空"
		})
	}, {
		header : '自定义UI(customHtml)',
		dataIndex : "customHtml",
		menuDisabled : true,
		width : 300,
		editor : new Ext.form.TextField()
	}, {
		header : 'orderIndex',
		dataIndex : 'orderIndex',
		hidden : true,
		width : 80
	} ]);
	Plant = Ext.data.Record.create([ {
		name : 'id',
		type : 'string'
	}, {
		name : 'title',
		type : 'string'
	}, {
		name : 'tooltip',
		type : 'string'
	}, {
		name : 'iconCls',
		type : 'string'
	}, {
		name : 'iconClsChild',
		type : 'string'
	}, {
		name : 'handler',
		type : 'string'
	}, {
		name : 'orderIndex',
		type : "int"
	} , {
		name : 'customHtml',
		type : "string"
	}]);

	store = new Ext.data.Store({
		baseParams : {
			id : id
		},
		proxy : new Ext.data.HttpProxy({
			url : basePath + 'repository/form/buttons/getFormMeatadataButtonsJson?form_id='+form_id+'&formMetadataId='+formMetadataId
		}),
		reader : new Ext.data.JsonReader({
			totalProperty : "total",
			root : "root",
			id : "id"
		}, [ 'id', 'title', 'tooltip', 'iconCls', 'handler', 'orderIndex','iconClsChild','customHtml' ], Plant)
	});
	grid = new Ext.grid.EditorGridPanel({
		renderTo : 'grid',
		store : store,
		region : 'center',
		cm : cm,
		sm : sm,
		trackMouseOver : false,
		clicksToEdit : 1,
		loadMask : {
			msg : '正在加载数据，请稍候...'
		},
		border : false,
		enableDragDrop : true,
		viewConfig : {
			forceFit : true
		},
		listeners : {
			'bodyscroll' : function() {
				return false;
			}
		},
		tbar : [ {
			text : '添加',
			iconCls : 'iconNew',
			handler : function() {
				var count = store.getCount();
				if(count==0){
					//是主表
					if(is_master_dataset){
						for(var i=1;i<4;i++){
							if(i==1){
								var insertRowInd = store.data.length;
								var Plant = grid.getStore().recordType;
								var p = new Plant({});
								p.set('id', '');
								p.set('title', '保存');
								//p.set('tooltip', '保存');
								p.set('iconCls', 'btn btn-success');
								p.set('iconClsChild', 'fa fa-check right');
								p.set('handler', '');
								p.set('orderIndex', 0);
								grid.stopEditing();
								store.insert(insertRowInd, p);
								grid.startEditing(insertRowInd, 3);
							}else if(i==2){
								var insertRowInd = store.data.length;
								var Plant = grid.getStore().recordType;
								var p = new Plant({});
								p.set('id', '');
								p.set('title', '提交');
								//p.set('tooltip', '保存');
								p.set('iconCls', 'btn btn-success');
								p.set('iconClsChild', 'fa fa-check right');
								p.set('handler', '');
								p.set('orderIndex', 0);
								grid.stopEditing();
								store.insert(insertRowInd, p);
								grid.startEditing(insertRowInd, 3);
							}else if(i==3){
								var insertRowInd = store.data.length;
								var Plant = grid.getStore().recordType;
								var p = new Plant({});
								p.set('id', '');
								p.set('title', '取消');
								//p.set('tooltip', '保存');
								p.set('iconCls', 'btn btn-danger');
								p.set('iconClsChild', 'btn-label glyphicon glyphicon-remove');
								p.set('handler', '');
								p.set('orderIndex', 0);
								grid.stopEditing();
								store.insert(insertRowInd, p);
								grid.startEditing(insertRowInd, 3);
							}
						}
					}else{
						for(var i=1;i<=4;i++){
							if(i==1){
								var insertRowInd = store.data.length;
								var Plant = grid.getStore().recordType;
								var p = new Plant({});
								p.set('id', '');
								p.set('title', '添加');
								//p.set('tooltip', '保存');
								p.set('iconCls', 'btn btn-primary btn-sm');
								p.set('iconClsChild', 'fa fa-edit');
								p.set('handler', '');
								p.set('orderIndex', 0);
								grid.stopEditing();
								store.insert(insertRowInd, p);
								grid.startEditing(insertRowInd, 3);
							}else if(i==2){
								var insertRowInd = store.data.length;
								var Plant = grid.getStore().recordType;
								var p = new Plant({});
								p.set('id', '');
								p.set('title', '删除');
								//p.set('tooltip', '保存');
								p.set('iconCls', 'btn btn-danger btn-sm');
								p.set('iconClsChild', 'fa fa-times');
								p.set('handler', '');
								p.set('orderIndex', 0);
								grid.stopEditing();
								store.insert(insertRowInd, p);
								grid.startEditing(insertRowInd, 3);
							}else if(i==3){
								var insertRowInd = store.data.length;
								var Plant = grid.getStore().recordType;
								var p = new Plant({});
								p.set('id', '');
								p.set('title', '保存');
								//p.set('tooltip', '保存');
								p.set('iconCls', 'btn btn-success btn-sm');
								p.set('iconClsChild', 'fa fa-check');
								p.set('handler', '');
								p.set('orderIndex', 0);
								grid.stopEditing();
								store.insert(insertRowInd, p);
								grid.startEditing(insertRowInd, 3);
							}
						}
					}
				}else{
					var insertRowInd = store.data.length;
					var Plant = grid.getStore().recordType;
					var p = new Plant({});
					p.set('id', '');
					p.set('title', '');
					p.set('tooltip', '');
					p.set('iconCls', '');
					p.set('handler', '');
					p.set('orderIndex', 0);
					grid.stopEditing();
					store.insert(insertRowInd, p);
					grid.startEditing(insertRowInd, 3);
				}

			}
		}, '-', {
			text : '保存',
			iconCls : 'iconSave',
			handler : function() {
				saveGrid();
			}
		}, '-', {
			text : '删除',
			iconCls : 'iconDelete',
			id : "deleteC",
			disabled : true,
			handler : function() {
				remove();
			}
		}, '-', {
			text : '刷新',
			tooltip : '刷新',
			handler : function() {
				store.reload();
			},
			iconCls : 'iconRefresh'
		}, '->' ]
	});
	viewport = new Ext.Viewport({
		layout : 'border',
		items : [ grid ]
	});
	store.load();
	grid.getSelectionModel().on('selectionchange', function(t) {
		Ext.getCmp("deleteC").setDisabled(t.getSelections().length === 0);
	});
	var ddrow = new Ext.dd.DropTarget(grid.container, {
        ddGroup : 'GridDD',
        copy    : false,
        notifyDrop: function(dd, e, data) {
        	       var rows = data.selections;
        	       //data.rowIndex
        	       //var index = dd.getDragData(e).rowIndex;
        	       if(dd.getDragData(e).rowIndex==undefined ){
        	       	  return;
        	       	}
        	       var  sourceId = rows[0].id;
        	       var  targetId = dd.getDragData(e).selections[0].id;
        	       handleSave(sourceId,targetId);
        	       return;
        	}
 });
});
function saveGrid() {
	var m = store.getModifiedRecords();
	if (m.length > 0) {
		for (var i = 0, len = m.length; i < len; i++) {
			var rec = m[i];
		}
		var temp = 0;
		var json = [];
		Ext.each(m, function(item) {
			json.push(item.data);
		});
		store.commitChanges();
		Ext.Ajax.request({
			url : basePath + 'repository/form/buttons/saveFormMetadataButton',
			method : 'POST',
			params : {
				datas : Ext.util.JSON.encode(json),
				form_id : form_id,
				formMetadataId:formMetadataId
			},
			failure : function(response, options) {
				Ext.MessageBox.alert('操作失败', '操作失败！可能是网络超时！');
				return false;
			},
			success : function(response, options) {
				if (response.responseText == '1') {
					Ext.MessageBox.alert('提示', " 保 存 成 功! ");
					store.reload();
				} else if (response.responseText == '-1') {
					Ext.MessageBox.alert('提示', " 保 存 失 败! ");
					return false;
				}
			}
		});

	} else {
		Ext.MessageBox.alert('提示', '当前没有需要保存的记录!');
		return false;
	}
}

function remove() {
	var selectedKeys = grid.selModel.selections.keys;
	Ext.MessageBox.confirm('提示', '确定删除选定的字段?', function(btn) {
		if (btn == 'yes') {
			Ext.Ajax.request({
				url : basePath + 'repository/form/buttons/removeFormMetadataButton',
				method : 'POST',
				params : {
					ids : selectedKeys,
					form_id : form_id,
					formMetadataId:formMetadataId
				},
				failure : function(response, options) {
					Ext.MessageBox.alert('操作失败', '操作失败！可能是网络超时！');
					return false;
				},
				success : function(response, options) {
					if (response.responseText == 'ok') {
						store.commitChanges();
						store.reload();
						Ext.MessageBox.alert('提示', " 删 除 成 功! ");
					}
				}
			});
		}

	});
}

function handleSave(sourceId,targetId){
	  Ext.getBody().mask("保存排序...");
	  Ext.Ajax.request({
				url : basePath+'repository/form/buttons/sortGird',
				method : 'POST',
				params : {
					 sourceId: sourceId,
					 targetId: targetId,
					 form_id:form_id,
					 form_er_id:formMetadataId
				},
				failure : function(response, options) {
					Ext.MessageBox.alert('操作失败', '操作失败！可能是网络超时！');
					return false;
				},
				success : function(response, options) {
					Ext.getBody().unmask();
					if(response.responseText!='1'){
						Ext.MessageBox.alert('提示', " 排序发生错误，请刷新重新重试! ");
					}else{
							store.reload();
						}
				}
			});	  
	}